/**
 * @file
 *
 * @data 10.05.2016
 * @author: Anton Bondarev
 */
#include <errno.h>
#include <stdint.h>

#include <util/log.h>

#include <kernel/irq.h>

#include <net/skbuff.h>
#include <net/netdevice.h>
#include <net/l0/net_entry.h>
#include <net/l2/ethernet.h>
#include <net/inetdevice.h>
#include <net/util/show_packet.h>

#include <asm/io.h>

#include <embox/unit.h>

EMBOX_UNIT_INIT(mipsnet_init);

#define BASE_ADDR    OPTION_GET(NUMBER,base_addr)
#define IRQ_NUM      OPTION_GET(NUMBER,irq_num)

/*
 * Net status/control block as seen by sw in the core.
 */
struct mipsnet_regs {
	/*
	 * Device info for probing, reads as MIPSNET%d where %d is some
	 * form of version.
	 */
	uint64_t devId;              /*0x00 */

	/*
	 * read only busy flag.
	 * Set and cleared by the Net Device to indicate that an rx or a tx
	 * is in progress.
	 */
	uint32_t busy;               /*0x08 */

	/*
	 * Set by the Net Device.
	 * The device will set it once data has been received.
	 * The value is the number of bytes that should be read from
	 * rxDataBuffer.  The value will decrease till 0 until all the data
	 * from rxDataBuffer has been read.
	 */
	uint32_t rxDataCount;        /*0x0c */
#define MIPSNET_MAX_RXTX_DATACOUNT (1 << 16)

	/*
	 * Settable from the MIPS core, cleared by the Net Device.
	 * The core should set the number of bytes it wants to send,
	 * then it should write those bytes of data to txDataBuffer.
	 * The device will clear txDataCount has been processed (not
	 * necessarily sent).
	 */
	uint32_t txDataCount;        /*0x10 */

	/*
	 * Interrupt control
	 *
	 * Used to clear the interrupted generated by this dev.
	 * Write a 1 to clear the interrupt. (except bit31).
	 *
	 * Bit0 is set if it was a tx-done interrupt.
	 * Bit1 is set when new rx-data is available.
	 *    Until this bit is cleared there will be no other RXs.
	 *
	 * Bit31 is used for testing, it clears after a read.
	 *    Writing 1 to this bit will cause an interrupt to be generated.
	 *    To clear the test interrupt, write 0 to this register.
	 */
	uint32_t interruptControl;   /*0x14 */
#define MIPSNET_INTCTL_TXDONE     (1u << 0)
#define MIPSNET_INTCTL_RXDONE     (1u << 1)
#define MIPSNET_INTCTL_TESTBIT    (1u << 31)

	/*
	 * Readonly core-specific interrupt info for the device to signal
	 * the core. The meaning of the contents of this field might change.
	 */
	/* XXX: the whole memIntf interrupt scheme is messy: the device
	 * should have no control what so ever of what VPE/register set is
	 * being used.
	 * The MemIntf should only expose interrupt lines, and something in
	 * the config should be responsible for the line<->core/vpe bindings.
	 */
	uint32_t interruptInfo;      /*0x18 */

	/*
	 * This is where the received data is read out.
	 * There is more data to read until rxDataReady is 0.
	 * Only 1 byte at this regs offset is used.
	 */
	uint32_t rxDataBuffer;       /*0x1c */

	/*
	 * This is where the data to transmit is written.
	 * Data should be written for the amount specified in the
	 * txDataCount register.
	 * Only 1 byte at this regs offset is used.
	 */
	uint32_t txDataBuffer;       /*0x20 */
};

static int mipsnet_xmit(struct net_device *dev, struct sk_buff *skb) {
	struct mipsnet_regs *regs;
	int i;
	uint8_t *pdata;

	show_packet(skb->mac.raw, skb->len, "xmit");

	regs = (struct mipsnet_regs *)dev->base_addr;
	pdata = skb->mac.raw;

	out32(skb->len, &regs->txDataCount);
	for(i = 0; i < skb->len; i++) {
		out32((uint32_t)*pdata, &regs->txDataBuffer);
		pdata++;
	}

	skb_free(skb);
	return 0;
}

static int mipsnet_open(struct net_device *dev) {
	struct mipsnet_regs *regs;

	regs = (struct mipsnet_regs *)dev->base_addr;
	out32(MIPSNET_INTCTL_TESTBIT, &regs->interruptControl);

	return 0;
}

static int mipsnet_set_macaddr(struct net_device *dev, const void *addr) {
	return 0;
}

static const struct net_driver mipsnet_drv_ops = {
	.xmit = mipsnet_xmit,
	.start = mipsnet_open,
	.set_macaddr = mipsnet_set_macaddr
};

static int mipsnet_rx(struct net_device *dev, size_t len) {
	struct sk_buff *skb;
	uint8_t *pdata;
	struct mipsnet_regs *regs;

	if (!len)
			return len;

	regs = (struct mipsnet_regs *)dev->base_addr;

	skb = skb_alloc(len);
	if (!skb) {
			dev->stats.rx_dropped++;
			return -ENOMEM;
	}
	pdata = (uint8_t*) skb->mac.raw;
	for (; len > 0; len--, pdata++) {
		*pdata = in32(&regs->rxDataBuffer);
	}

	show_packet(skb->mac.raw, skb->len, "rx");
	skb->dev = dev;

	netif_rx(skb);

	dev->stats.rx_packets++;
	dev->stats.rx_bytes += len;

	return len;
}

static irq_return_t mipsnet_interrupt_handler(unsigned int irq, void *dev_id) {
	struct net_device *dev = dev_id;
	uint32_t int_flags;
	irq_return_t ret = IRQ_NONE;
	struct mipsnet_regs *regs;

	if (irq != dev->irq)
		goto out_badirq;

	regs = (struct mipsnet_regs *)dev->base_addr;

	/* TESTBIT is cleared on read. */
	int_flags = in32(&regs->interruptControl);
	if (int_flags & MIPSNET_INTCTL_TESTBIT) {
			/* TESTBIT takes effect after a write with 0. */
			out32(0, &regs->interruptControl);
			ret = IRQ_HANDLED;
	} else if (int_flags & MIPSNET_INTCTL_TXDONE) {
			/* Only one packet at a time, we are done. */
			dev->stats.tx_packets++;
			out32(MIPSNET_INTCTL_TXDONE, &regs->interruptControl);
			ret = IRQ_HANDLED;
	} else if (int_flags & MIPSNET_INTCTL_RXDONE) {
			mipsnet_rx(dev, in32(&regs->rxDataCount));
			out32(MIPSNET_INTCTL_RXDONE, &regs->interruptControl);
			ret = IRQ_HANDLED;
	}

	return ret;

out_badirq:
	 log_info("%s: irq %d for unknown device\n", dev->name, irq);

	 return ret;
}


static int mipsnet_init(void) {
	struct net_device *netdev;
	int err;

	netdev = etherdev_alloc(0);
	if (!netdev) {
		return -ENOMEM;
	}

	/*
	 * TODO: probe for these or load them from PARAM
	 */
	netdev->base_addr = BASE_ADDR;
	netdev->irq = IRQ_NUM;
	netdev->drv_ops = &mipsnet_drv_ops;

	err = irq_attach(IRQ_NUM, mipsnet_interrupt_handler, 0, netdev, "mipsnet");
	if (err) {
		return err;
	}

	return inetdev_register_dev(netdev);
}
